<template>
  <div>
    <!-- 面包屑导航 -->
    <BreadCrumbs name1="用户管理" name2="用户列表"></BreadCrumbs>
    <!-- 卡片内容 -->
    <el-card>
      <el-row type="flex" justify="space-between">
        <el-col
          style="
            margin-left: 16px;
            display: flex;
            flex-wrap: wrap;
            white-space: nowrap;
          "
        >
          <el-form
            :inline="true"
            :model="queryInfo"
            ref="form"
            class="form-inline"
          >
            <el-form-item label="用户ID" prop="userId">
              <el-input
                placeholder="请输入内容"
                size="small"
                v-model="queryInfo.userId"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item label="用户性别" prop="gender">
              <el-select size="small" v-model="queryInfo.gender" clearable>
                <el-option label="男" value="MALE"></el-option>
                <el-option label="女" value="FEMALE"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="getSearch"
                >搜索</el-button
              >
              <el-button size="small" @click="reset()">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <dk-table
        ref="table"
        :column="column"
        :pagination="paginationObjs"
        :tableData="tableData"
        shadow="never"
        :height="tableHeight"
      >
        <template #today_status="{ scope }">
          <!-- 0正常，1警告 -->
          <!-- {{ scope.daily_health[0]? scope.daily_health[0].today_status : '' }} -->
          <span v-if="!scope.daily_health[0]"></span>
          <span
            v-else-if="scope.daily_health[0].today_status"
            style="
              background-color: #e52f10;
              width: 45px;
              height: 20px;
              box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 1);
            "
          ></span>
          <span
            v-else
            style="
              background-color: #089c14;
              width: 45px;
              height: 20px;
              box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 1);
            "
          ></span>
        </template>
      </dk-table>
    </el-card>

    <el-dialog
      top="20%"
      title="添加标签"
      :visible.sync="tag_dialog.visible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="tag_dialog.form"
        ref="tagForm"
        label-width="80px"
        :rules="tag_dialog.rules"
        style="padding-right: 40px"
      >
        <el-form-item label="标签" prop="tag" required>
          <el-input v-model="tag_dialog.form.tag"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tag_dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="tagOnSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="内容填写"
      :visible.sync="edit_dialog.visible"
      :close-on-click-modal="false"
    >
      <el-form
        label-position="top"
        :model="edit_dialog.form"
        ref="editForm"
        label-width="180px"
        :rules="edit_dialog.rules"
        style="padding-right: 40px; max-height: 50vh; overflow: auto"
      >
        <el-form-item label="电话" prop="phone">
          <el-input v-model="edit_dialog.form.phone"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nick_name">
          <el-input v-model="edit_dialog.form.nick_name"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="edit_dialog.form.age"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="edit_dialog.form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="合并症" prop="symptom">
          <el-select v-model="edit_dialog.form.symptom" multiple>
            <el-option
              v-for="(item, index) in edit_dialog.symptomOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="干体质量（kg）" prop="initial_dry_weight">
          <el-input
            v-model.number="edit_dialog.form.initial_dry_weight"
          ></el-input>
        </el-form-item>
        <el-form-item label="今日体质量（kg）" prop="today_weight">
          <el-input
            v-model.number="edit_dialog.form.daily_health[0].today_weight"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="静息心率（次/分）"
          prop="initial_resting_heart_rate"
        >
          <el-input
            v-model="edit_dialog.form.initial_resting_heart_rate"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="今日静息心率（次/分）"
          prop="today_resting_heart_rate"
        >
          <el-input
            v-model="edit_dialog.form.daily_health[0].today_resting_heart_rate"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="edit_dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="editOnSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tag_dialog: {
        visible: false,
        form: {
          id: "",
          tag: "",
        },
        rules: {
          tag: [
            {
              required: true,
              message: "请输入标签",
              trigger: "blur",
            },
            {
              max: 20,
              message: "长度不能超过20个字符",
            },
          ],
        },
      },
      edit_dialog: {
        visible: false,
        form: {
          id: "",
          phone: "31",
          nick_name: "test",
          age: 45,
          tag: "44rqwe11",
          gender: null,
          initial_resting_heart_rate: 0,
          initial_dry_weight: 0,
          symptom: [
            // {
            //   id: 1,
            //   name: '花粉症',
            // },
          ],
          daily_health: [
            {
              today_dry_weight: "",
              today_weight: "",
              today_resting_heart_rate: "",
            },
          ],
        },
        symptomOptions: [],
        rules: {
          phone: [
            { required: true, message: "请输入电话号码", trigger: "blur" },
            {
              validator: (rule, value, callback) => {
                if (!/^1[3456789]\d{9}$/.test(value)) {
                  callback(new Error("请输入正确的电话号码"));
                } else {
                  callback();
                }
              },
            },
          ],
          nick_name: [
            { required: true, message: "请输入昵称", trigger: "blur" },
          ],
          age: [
            { required: true, message: "请输入年龄", trigger: "blur" },
            {
              // 必须是数字
              validator: (rule, value, callback) => {
                if (!/^[0-9]*$/.test(value)) {
                  callback(new Error("请输入数字"));
                } else {
                  callback();
                }
              },
            },
          ],
          tag: [{ required: true, message: "请输入标签", trigger: "blur" }],
          gender: [
            { required: true, message: "请选择性别", trigger: "change" },
          ],
          symptom: [
            { required: true, message: "请选择合并症", trigger: "change" },
          ],
          initial_dry_weight: [
            { required: true, message: "请输入干体质量", trigger: "blur" },
            {
              //  包括小数和数字
              validator: (rule, value, callback) => {
                if (
                  !/^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)$/.test(
                    value
                  )
                ) {
                  callback(new Error("请输入数字"));
                } else {
                  callback();
                }
              },
            },
          ],
          initial_resting_heart_rate: [
            { required: true, message: "请输入静息心率", trigger: "blur" },
            {
              //  包括小数和数字
              validator: (rule, value, callback) => {
                if (
                  !/^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]z\d+([eE][+-]?\d+)?)$/.test(
                    value
                  )
                ) {
                  callback(new Error("请输入数字"));
                } else {
                  callback();
                }
              },
            },
          ],
        },
      },
      queryInfo: {
        userId: null,
        gender: null,
      },
      tableData: [],
      column: [
        {
          value: "userId",
          name: "用户ID",
        },
        {
          value: "phone",
          name: "手机号",
          width: 200,
        },
        {
          value: "gender",
          name: "性别",
          format: (val) =>
            val === "MALE" ? "男" : val === "FEMALE" ? "女" : "其他",
        },
        {
          value: "age",
          name: "用户年龄",
        },

        {
          value: "weight",
          name: "体重",
          width: 150,
          format: (val) => `${val || 0} KG`,
        },
        {
          value: "comorbidities",
          name: "合并症",
          format: (val) => {
            return val?.map((i) => i.name).join("/") || "--";
          },
        },
        {
          value: "totalPoint",
          name: "当前积分",
          width: 150,
          format: (val) => val || 0,
        },
        {
          width: 150,
          value: "operate",
          name: "操作",
          fixed: "right",
          type: "button",
          buttonList: [
            {
              type: "no-tooltip",
              name: "详情",
              fun: (row) => {
                this.$router.push({
                  path: "/users/detail/" + row.userId,
                });
              },
              color: "text",
            },
            {
              type: "no-tooltip",
              name: "清除积分",
              fun: async (row) => {
                await this.$http.get(
                  `/diet/admin/user/clear-point/${row.userId}`
                );
                this.getUserList();
              },
              color: "text",
            },
          ],
        },
      ],
      paginationObjs: {
        paginationChange: function () {
          this.getUserList();
        }.bind(this),
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      userList: [],
    };
  },

  created() {
    this.getUserList();
    this.getTableHeight();
  },
  methods: {
    getSearch() {
      this.paginationObjs.pageNo = 1;
      this.getUserList();
    },
    async getUserList() {
      const { data, code, msg } = await this.$http({
        url: "/diet/admin/user",
        methods: "get",
        params: {
          ...this.queryInfo,
          pageNo: this.paginationObjs.pageNo,
          pageSize: this.paginationObjs.pageSize,
        },
      });
      if (code) return this.$message.error(msg);
      this.paginationObjs.total = data.total;
      this.tableData = data.list;
    },
    async getSymptomOptions() {
      const { code, data, msg } = await this.$http.get("/api/symptom");
      if (code) return this.$message.error(msg);
      this.edit_dialog.symptomOptions = data.map((item) => {
        return {
          value: item.id,
          label: item.name,
        };
      });
    },
    async tagOnSubmit() {
      try {
        await this.$refs.tagForm.validate();
        const { code, msg } = await this.$http.post("/api/user/base_info", {
          tag: this.tag_dialog.form.tag,
          userId: this.tag_dialog.form.id,
        });
        if (code) return this.$message.error(msg);
        this.tag_dialog.visible = false;
        this.$message.success("添加成功");
        this.$refs.tagForm.resetFields();
        await this.getUserList();
      } catch (error) {
        this.$message.error("请正确填写");
      }
    },
    async editOnSubmit() {
      console.log(this.edit_dialog.form);
      try {
        await this.$refs.editForm.validate();
        const userId = this.edit_dialog.form.id;
        const res = await Promise.all([
          await this.$http.post("/api/user/base_info", {
            ...this.edit_dialog.form,
            userId,
          }),
          await this.$http.post("/api/user/symptom", {
            symptom_ids: this.edit_dialog.form.symptom,
            userId,
          }),
          await this.$http.post("/api/user/daily_health", {
            ...this.edit_dialog.form.daily_health,
            userId,
          }),
        ]);

        if (res.code) return this.$message.error(res.msg);
        this.edit_dialog.visible = false;
        this.$message.success("修改成功");
        this.$refs.editForm.resetFields();
        await this.getUserList();
      } catch (error) {
        console.log(error);
        this.$message.error("请正确填写");
      }
    },
    async reset() {
      await this.$refs["form"].resetFields();
      await this.getUserList();
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.el-table {
  margin-top: 15px;
}

.el-pagination {
  margin-top: 15px;
}

.form-inline {
  display: flex;
  column-gap: 12px;
  flex-wrap: wrap;
}

::v-deep {
  .el-input {
    max-width: 120px !important;
  }
  .el-button--text {
    margin-right: 10px;
  }

  .el-form .el-input {
    width: 100%;
    max-width: none !important;
  }
}
</style>
